<template>
  <view style="overflow: hidden">
    <up-navbar v-if="VisibleandHidden" :title="title" :autoBack="false" placeholder @leftClick="closePopup"></up-navbar>
    <view class="box-headinput">
      <view class="search-bar">
        <u-icon name="search" size="18" color="#999" class="search-icon" />
        <input v-model="keywordvalue" class="search-input" type="text" placeholder="请输入名称"
          placeholder-class="search-placeholder" />
      </view>
    </view>

    <view class="box-head">
      <PickerHeader ref="refUniMallHead" @change="tabChange"></PickerHeader>
    </view>


    <scroll-view class="apply-menu" scroll-y="true" :style="listHeightStyle">
      <view class="box-list">
        <view v-if="hasUser" class="select-all">
          <radio :checked="isAllChecked" @click="toggleSelectAll" style="transform: scale(0.8)" />
          <text style="margin-left: 8px;">全选</text>
        </view>
        <template v-for="item in currentData" :key="item.id">
          <view class="box-list-item" :class="[
            item.children && item.children.length ? 'box-list-item-dept-icon' : '',
            item.type === 'user' ? 'box-list-item-user' : 'box-list-item-dept'
          ]">
            <checkbox @click="MultiplechoiceClickItem(item)" v-show="_entry == 'component' && item.type === 'user'"
              style="transform: scale(0.8)" :checked="setChecked(item)" />

            <view class="box-list-item-dept-pic" v-if="item.type === 'dept'">
              <image src="@/static/dept-icon.png"></image>
            </view>
            <view class="box-list-item-user-pic" v-else>
              <image-local v-if="item.avatar" :id="item.id" :url="item.avatar" radius="10rpx" width="40px"
                height="50px"></image-local>
              <text v-else>{{ getUserName(item.name) }}</text>
            </view>
            <view class="box-list-item-right" @click="handelClickItem(item)">
              <view class="box-list-item-text">{{ item.name }} {{ item.children && item.children.length > 0 ?
                `（${item.children.length}）` : '' }}</view>
              <!-- 角色标签 职务 -->
              <view class="box-list-item-user-tag" v-if="item.type === 'user' && item.tag && item.type.length > 0">
                <text v-for="(tag, tagIndex) in item.tag">{{ tag }}</text>
              </view>
              <!-- 部门切换下级 -->
              <view class="box-list-item-user-tag tag-c" v-if="item.type === 'dept'"
                @click="handelClickItem(item, true)">
                <text style="font-size: 30rpx;">({{ item.person_num + '人' }})</text>
              </view>
            </view>
          </view>
        </template>
      </view>
    </scroll-view>

    <view class="select-container" v-show="_entry == 'component'">
      <view class="select-left">
        <text>已选择（{{ selection.length }}）:</text>
      </view>

      <!-- 多选左右滚动 -->
      <scroll-view class="scrollContainer" scroll-x>
        <view style="display: flex;" @click="show = true">
          <view v-for="item in selection" :key="item.id" class="select-item">
            <!-- #ifdef APP-PLUS -->
            <image-local style="margin-left: 10rpx;" v-if="item.avatar" :id="item.id" :url="item.avatar" radius="6rpx"
              width="72rpx" height="72rpx"></image-local>
            <text v-else>{{ item.name || item.username }}</text>
            <!-- #endif -->

            <!-- #ifdef H5 -->
            <view class="h5-image-wrapper" v-if="item.avatar">
              <image :src="item.avatar" :style="{ width: '72rpx', height: '72rpx', borderRadius: '6rpx' }"
                @error="handleH5ImageError(item)" mode="aspectFill" />
              <text v-if="item.showTextInstead" class="fallback-text">{{ getFallbackName(item.name ||
                item.username) }}</text>
            </view>
            <text v-else>{{ item.name || item.username }}</text>
            <!-- #endif -->
          </view>
        </view>
      </scroll-view>
      <view class="select-right">
        <up-button @click="submit" :customStyle="{ border: 'none', width: '92rpx', height: '52rpx' }"
          :disabled="selection.length == 0" type="primary" text="确定"></up-button>
      </view>
    </view>
    <!-- 人员弹出框 -->
    <up-popup :show="show" @close="show = false"
      :customStyle="{ height: '65vh', borderTopLeftRadius: '24rpx', borderTopRightRadius: '24rpx' }" mode="bottom">
      <!-- 顶部操作栏 -->
      <view class="popup-header">
        <view class="popup-close" @click="show = false">
          <up-icon name="close" :size="20" color="#666"></up-icon>
        </view>
        <view class="popup-title">已选择 ({{ selection.length }})</view>
        <view class="popup-confirm" @click="show = false">完成</view>
      </view>

      <!-- 人员列表 -->
      <scroll-view scroll-y class="popup-content">
        <view v-for="item in selection" :key="item.id" class="select-item">
          <view class="item-info">
            <view class="item-avatar">
              <image v-if="item.avatar" :id="item.id" :src="item.avatar" style="width: 80rpx;height: 80rpx;"></image>
              <text v-else class="avatar-text">{{ getInitials(item.name || item.username) }} </text>
            </view>
            <view class="item-name">{{ item.name || item.username }} </view>
          </view>
          <up-button type="error" size="size" plain style="width: 200rpx;"
            :customStyle="{ border: 'none', padding: '0 20rpx', height: '56rpx', borderRadius: '28rpx' }"
            @click="removeAndAdd(item)" text="移除"></up-button>
        </view>

        <!-- 空状态提示 -->
        <view v-if="selection.length === 0" class="empty-tip">
          <up-icon name="list" size="48" color="#ccc"></up-icon>
          <view class="empty-text">暂无选择人员</view>
        </view>
      </scroll-view>
    </up-popup>

  </view>
</template>

<script>
import base from '@/apis/cloud/base';
import ImageLocal from '@/components/image-local/image-local.vue';
import { SysAvatar } from '@/utils/sql/avatar';
import { getCurrentInstance } from "vue";
import PickerHeader from './picker-header.vue';
const AvaterBaseUrl = "https://cloud.mfarmers.com/dist/interface/public/upload/avatar/";
export default {
  components: {
    PickerHeader,
    ImageLocal
  },

  props: {
    // page页面使用 component组件使用
    entry: {
      type: String,
      default: 'page'
    },
    type: {
      type: String,
      default: 'user'
    },
    multiple: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      show: false,
      currentData: [],
      defaultHeadList: { name: '江苏绿港', id: '1' },
      dataList: [{
        id: 1,
        name: "江苏绿港",
        type: "dept",
        person_num: 400
      }],
      selection: [],
      topHeight: 0, // 动态计算的高度
      listHeightStyle: {}, // 动态计算的样式
      keywordvalue: '',
      itemid: null,
      objid: null,
      title: '',
      VisibleandHidden: false,
      _multiple: false,
      _entry: 'page',
      _type: 'user',
      option: {},
      fuzhiItemid: '',
      Backupmultiple: [], // 存入点击过的所有项（用户+部门）
      AselectionList: []
    };
  },
  computed: {
    // 判断当前数据中是否有用户
    hasUser () {
      return this.currentData.some(item => item.type === 'user');
    },
    // 判断是否全选
    isAllChecked () {
      const userList = this.currentData.filter(i => i.type === 'user');
      if (userList.length === 0) return false;
      return userList.every(u => this.selection.some(s => this.getUserKey(s) === u.id));
    }
  },
  watch: {
    keywordvalue (val) {
      this.getCurrentData();
    },
  },
  onLoad (option) {
    this.option = option
    this.title = option.title || this.title // title名称
    this.VisibleandHidden = option.VisibleandHidden || this.VisibleandHidden // 导航栏显隐
    this._entry = option._entry || this.entry // 底部选中人员显示
    this._type = option._type || this.type // 类型
  },
  created () {
    let that = this
    const instance = getCurrentInstance().proxy;
    const eventChannel = instance.getOpenerEventChannel();
    eventChannel.on('MenberPicker', async function (data) {
      uni.showLoading({
        title: '加载中....'
      });
      let tempSelection = JSON?.parse(data?.imgheadList).map((item) => {
        let avatar
        if (item.avatar) {
          avatar = item.avatar
        } else {
          const phone = item.friend_phone || item.phone || item.avatar;
          avatar = AvaterBaseUrl + item.phone + '.jpg'
        }

        return {
          ...item,
        }
      })

      that.selection = [
        ...new Map(tempSelection.map(i => [that.getUserKey(i), i])).values()
      ];
      uni.hideLoading()
    })

    this.calculateListHeight();
  },
  mounted () {
    this.init();
  },
  methods: {
    // 全选/取消全选
    toggleSelectAll () {
      const userList = this.currentData.filter(i => i.type === 'user');
      const allSelected = userList.every(u => this.selection.some(s => this.getUserKey(s) === u.id));
      if (allSelected) {
        // 如果已经全选 -> 取消全选
        this.selection = this.selection.filter(sel => !userList.some(u => this.getUserKey(u) === sel.id));
      } else {
        // 否则加入 selection
        userList.forEach(u => {
          if (!this.selection.some(sel => this.getUserKey(sel) === u.id)) {
            this.selection.push(u);
          }
        });
      }
      this.selection = this.dedupe(this.selection); // 去重
    },
    getInitials (name) {
      if (!name) return '';
      const chinese = name.match(/[\u4e00-\u9fa5]/g);
      if (chinese && chinese.length >= 2) {
        return chinese[0] + chinese[chinese.length - 1];
      }
      return name.length > 2 ? name.substring(0, 2) : name;
    },
    closePopup () {
      uni.navigateBack({ delta: 1 });
    },
    calculateListHeight () {
      const windowHeight = window.innerHeight; // 视口高度
      const topHeight = this.topHeight; // 顶部安全高度
      const headerHeight = 97; // 顶部操作区域、搜索框等的高度

      // #ifdef APP-PLUS
      let app = uni.getSystemInfoSync();
      ;
      this.listHeightStyle = {
        height: `${app.windowHeight - 50}px`,
        overflowY: 'hidden',
        paddingBottom: '100rpx',
      };
      // #endif

      // #ifdef H5
      const listHeight = windowHeight - topHeight - headerHeight;
      this.listHeightStyle = {
        height: `${listHeight}px`,
        overflowY: 'hidden'
      };
      // #endif
    },
    handleH5ImageError (item) {
      this.$set(item, 'showTextInstead', true); // 添加响应式字段
    },
    getFallbackName (name) {
      if (!name) return '';
      if (name.length <= 2) return name;
      return name.slice(-2); // 取最后两个字
    },
    submit () {
      this.$emit('ok', this.selection);
      // ProcessRender 流程图
      if (this.VisibleandHidden) {
        this.jumpto()
      }
    },
    isEntry () {
      if (this._entry == 'page') return false;
    },
    async init (id) {
      if (Object.keys(this.defaultHeadList).length > 0) {
        this.$refs.refUniMallHead.addTab(this.defaultHeadList);
      }

      // 创建 sys_avatar
      //#ifdef APP-PLUS
      await SysAvatar.init();
      // #endif

      this.getCurrentData(1);
    },
    // 是否选中
    setChecked (item) {
      if (item.type === 'user') {
        return this.selection.some(u => this.getUserKey(u) === this.getUserKey(item));
      } else if (item.type === 'dept') {
        return this.selection.some(u => u.topDeptId === item.id);
      }
    },
    // 顶部部门切换
    tabChange (obj) {
      this.defaultHeadList = obj;
      this.getCurrentData(obj.id, true);
    },

    handelClickItem (item, change) {
      // 切换部门 获取数据
      if ((item.type === 'dept' && this._type != 'dept') || change) {
        this.getCurrentData(item.id);
        this.defaultHeadList = item;
        this.$refs.refUniMallHead.addTab({ name: item.name, id: item.id });
        return;
      }

      if (item.type === 'user') {
        item.topDeptId = this.defaultHeadList.id;
        this.removeAndAdd(item);
        this.selection = this.dedupe(this.selection);
      }
    },
    removeAndAdd (itemOrArray) {
      const items = Array.isArray(itemOrArray) ? itemOrArray : [itemOrArray];
      items.forEach(item => {
        const key = this.getUserKey(item);
        const index = this.selection.findIndex(u => this.getUserKey(u) === key);

        if (index !== -1) {
          // 已存在 -> 移除
          this.selection.splice(index, 1);
        } else {
          // 不存在 -> 添加
          this.selection.push(item);
        }

        // 备份
        if (!this.Backupmultiple.some(u => this.getUserKey(u) === key)) {
          this.Backupmultiple.push(item);
        }
      });
    },
    // 名称处理
    getUserName (name) {
      if (name.length === 0) {
        return '';
      } else if (name.length <= 2) {
        return name;
      } else if (name.length >= 3) {
        return name.substring(name.length - 2);
      }
    },
    async changeUpinput () {
      console.log('this.keywordvalue', this.keywordvalue)
    },
    // 获取数据
    async getCurrentData (id, topTabChange) {
      if (id !== this.defaultHeadList.id || topTabChange) {
        const msg = await base.WorkerTree({ deptId: id, type: this._type, keyword: this.keywordvalue });
        this.currentData = msg.data;
      }
    },
    jumpto () {
      let selection = this.selection.map(item => {
        return {
          username: item.name || item.username,
          id: item.cloud_worker_id || item.id || item.i.wid,
          avatar: item.avatar || AvaterBaseUrl + item.phone + '.jpg',
          cloud_worker_id: item.cloud_worker_id || item.id || item.i.wid
        }
      })
      uni.$emit('CreateGroupMemberPicker', JSON.stringify(selection))
      uni.navigateBack({ delta: 2 });
    },
    // 递归查找部门下所有用户（含子部门）
    async fetchUsersFromDept (deptId, visited = new Set()) {
      if (visited.has(deptId)) return [];
      visited.add(deptId);
      uni.showLoading({ title: '加载中...', mask: true });
      const res = await base.WorkerTree({
        deptId,
        type: this._type,
        keyword: this.keywordvalue
      });
      uni.hideLoading();
      const data = res.data || [];
      let users = [];
      for (const item of data) {
        if (item.type === 'user') {
          users.push({ ...item, parentDeptId: deptId });
        } else if (item.type === 'dept') {
          const subUsers = await this.fetchUsersFromDept(item.id, visited);
          users = users.concat(subUsers);
        }
      }
      return users;
    },
    dedupe (list) {
      return [...new Map(list.map(i => [this.getUserKey(i), i])).values()];
    },
    // 批量选择部门或人员
    async MultiplechoiceClickItem (item) {
      if (item.type === 'user') {
        // 切换用户选中状态
        this.removeAndAdd(item);
        this.selection = this.dedupe(this.selection);
        return;
      }

      if (item.type === 'dept') {
        // 获取部门下所有用户，包括子部门
        const users = await this.fetchUsersFromDept(item.id);
        const usersWithTopDept = users.map(u => ({ ...u, topDeptId: item.id }));

        // 判断部门下是否有已选用户
        const alreadySelected = usersWithTopDept.some(u =>
          this.selection.some(s => this.getUserKey(s) === u.id)
        );

        if (alreadySelected) {
          // 取消部门：移除该部门下所有用户
          this.selection = this.selection.filter(u => u.topDeptId !== item.id);
          // 移除部门备份
          this.Backupmultiple = this.Backupmultiple.filter(
            u => u.topDeptId !== item.id && this.getUserKey(u) !== item.id
          );
        } else {
          console.log('item', item);

          // 勾选部门：加入所有用户
          this.removeAndAdd(usersWithTopDept);
          // 备份部门本身
          if (!this.Backupmultiple.some(i => (i.wid || i.id) === item.id)) {
            this.Backupmultiple.push({ ...item, topDeptId: item.id });
          }
        }
      }

      this.selection = this.dedupe(this.selection);
      this.Backupmultiple = this.dedupe(this.Backupmultiple);
    },
    getUserKey (item) {
      return item.cloud_worker_id || item.wid || item.uid || item.id;
    },

  }
};
</script>

<style lang="scss" scoped>
.h5-image-wrapper {
  position: relative;
  display: inline-block;
}


.search-bar {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 10px;
  padding: 0 20rpx;
  height: 60rpx;
  box-sizing: border-box;
}

.search-icon {
  margin-right: 10rpx;
}

.search-input {
  flex: 1;
  border: none;
  background-color: transparent;
  font-size: 28rpx;
  color: #333;
}

.search-placeholder {
  color: #999;
}


.fallback-text {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20rpx;
  color: white;
  background-color: rgba(0, 0, 0, 0.3); // 可选背景色增强可读性
  text-align: center;
  line-height: 70rpx !important;
  width: 70rpx !important;
  height: 70rpx !important;
  color: #fff;
  font-size: 28rpx;
  font-weight: 500;
}

.box-headinput {
  position: fixed;
  left: 0px;
  width: 100%;
  height: 48px;
  padding-left: 20rpx;
  padding-right: 20rpx;
  background: #ffffff;
  box-sizing: border-box;
  overflow-y: hidden;
  z-index: 9999;
}


.box-head {
  position: fixed;
  left: 0px;
  width: 100%;
  height: 48px;
  //#ifdef APP-PLUS
  top: 210rpx;
  // #endif

  // #ifdef H5
  top: 150rpx;
  // #endif
  background: #ffffff;
  padding-left: 17px;
  box-sizing: border-box;
  overflow-y: hidden;
  z-index: 9999;
}

.box-list {
  //#ifdef APP-PLUS
  padding-top: 70px;
  // #endif

  // #ifdef H5
  padding-top: 82px;

  // #endif
  .box-list-item {
    position: relative;
    height: 60px;
    display: flex;
    align-items: center;
    padding: 0 14px;
    box-sizing: border-box;
    background: #ffffff;
    margin-bottom: 1px;

    &:active {
      background: #f2f3f4;
    }

    &:last-child {
      margin-bottom: 0px;
    }

    .box-list-item-dept-pic {
      width: 40px;
      height: 40px;
      background: rgba(55, 127, 255, 0.1);
      border-radius: 10rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 14px;
      overflow: hidden;

      image {
        width: 20px;
        height: 20px;
      }
    }

    .box-list-item-user-pic {
      width: 40px;
      height: 40px;
      background: #377fff;
      border-radius: 10rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 14px;
      overflow: hidden;

      image {
        width: 40px;
        height: 40px;
      }

      text {
        color: #ffffff;
        font-size: 12px;
      }
    }

    .box-list-item-right {
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex: 1;
    }

    .box-list-item-text {
      color: #333333;
      font-size: 16px;
    }

    .box-list-item-user-tag {
      text {
        box-sizing: border-box;
        border-radius: 8px;
        padding: 4px 8px;
        font-size: 10px;
        margin-left: 5px;

        &:first-child {
          margin-left: 0px;
        }

        &:nth-child(1) {
          background: rgba(49, 210, 144, 0.05);
          color: #31d290;
        }

        &:nth-child(2) {
          background: rgba(55, 127, 255, 0.05);
          color: #377fff;
        }
      }
    }

    .tag-c {
      text {
        color: #377fff !important;
      }
    }

    &.box-list-item-dept-icon {
      &::after {
        content: '';
        position: absolute;
        width: 5px;
        height: 10px;
        top: 26px;
        right: 15px;
        background: url(@/static/more.png) no-repeat;
      }
    }
  }
}

.select-container {
  position: fixed;
  box-sizing: border-box;
  bottom: 0;
  padding: 30rpx 20rpx;
  width: 100vw;
  display: flex;
  align-items: center;
  background-color: #fff;
  border-top: 1px solid #E1E3E5;

  .scrollContainer {
    width: 60%;
    display: flex;
  }

  .select-left {
    font-size: 26rpx;
    width: 25%;
  }

  .select-right {
    width: 10%;
  }
}

.single-item {
  text {
    font-size: 32rpx;
  }
}

.select-item {
  display: flex;
  align-items: center;
  justify-content: space-between;

  image {
    display: inline-block;
    width: 60rpx;
    height: 60rpx;
    border-radius: 6rpx;
    margin: 0 4rpx;
  }

  text {
    z-index: 99;
    margin-top: -4px !important;
    display: inline-block;
    width: 75rpx;
    height: 75rpx;
    text-align: center;
    font-size: 25rpx;
    line-height: 70rpx;
    border-radius: 6rpx;
    background-color: #2979ff;
    color: #fff;
    margin: 0 8rpx;
  }
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 32rpx;
  padding: 30rpx;
}

/* 弹出框头部 */
.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #f5f5f5;

  .popup-close {
    padding: 8rpx;
  }

  .popup-title {
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
  }

  .popup-confirm {
    color: #2979ff;
    font-size: 28rpx;
    padding: 8rpx 16rpx;
  }
}

/* 内容区域 */
.popup-content {
  height: calc(65vh - 100rpx);
  padding: 0 24rpx;

  .select-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24rpx 0;
    border-bottom: 1rpx solid #f5f5f5;

    &:last-child {
      border-bottom: none;
    }

    .item-info {
      display: flex;
      align-items: center;
      flex: 1;
    }

    .item-avatar {
      width: 100rpx;
      height: 100rpx;
      border-radius: 20%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 24rpx;

      .avatar-text {
        line-height: 80rpx;
        width: 80rpx;
        height: 80rpx;
        color: #fff;
        font-size: 28rpx;
        font-weight: 500;
      }
    }

    .item-name {
      width: 100rpx;
      font-size: 28rpx;
      color: #333;
      flex: 1;
    }
  }

  .empty-tip {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 60%;
    color: #999;

    .empty-text {
      margin-top: 16rpx;
      font-size: 28rpx;
    }
  }
}

.select-all {
  //#ifdef APP-PLUS
  padding-top: 10rpx;
  margin-left: 30rpx;
  // #endif

  // #ifdef H5
  margin-left: 26rpx;
  // #endif
}

.apply-menu {
  overflow-y: auto;
}
</style>
